package com.huahua.api.scheduled;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huahua.api.entity.dto.mofang.FormRecordListDto;
import com.huahua.api.entity.dto.mofang.UserInfoDto;
import com.huahua.api.entity.pojo.mofang.MofangCourseForm;
import com.huahua.api.entity.pojo.mofang.MofangLogin;
import com.huahua.api.service.MofangCourseFormService;
import com.huahua.api.service.MofangLoginService;
import com.huahua.api.util.MoFangUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;

import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author LoveHuahua
 * @date 2022年02月15日 22:14
 * @description believe in yourself
 */
@Configuration
@Slf4j
public class MoFangScheduleTask {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    @Autowired
    MofangLoginService mofangLoginService;
    @Autowired
    MofangCourseFormService mofangCourseFormService;
    Pattern compile = Pattern.compile("[0-9]+");

    @Autowired
    JavaMailSender sender;


    /**
     * 定时登录(2s 一循环)
     */
    @Scheduled(fixedRate = 1000 * 2)
    public void login() {
        List<MofangLogin> list = mofangLoginService.lambdaQuery().eq(MofangLogin::getStatus, 1).list();
        for (MofangLogin mofangLogin : list) {
            //遍历每一个链接
            String cookies = mofangLogin.getCookies();
            List<UserInfoDto> userInfo = MoFangUtil.getUserInfo(cookies);
            //空的 说明未登录
            if (userInfo.isEmpty()) {
                //尝试次数大于20 设置为登录失败
                if (mofangLogin.getCount() >= 20) {
                    mofangLoginService.update().eq("id", mofangLogin.getId()).set("status", 3).update();
                } else {
                    int val = mofangLogin.getCount();
                    mofangLoginService.update().eq("id", mofangLogin.getId()).set("count", ++val).update();
                }
            } else {
                //已登录
                mofangLoginService.lambdaUpdate().eq(MofangLogin::getId, mofangLogin.getId()).set(MofangLogin::getCookies, userInfo.get(0).getCookie()).set(MofangLogin::getStatus, 2).update();
                //添加课程信息
                for (UserInfoDto userInfoDto : userInfo) {
                    MofangCourseForm mofangCourseForm = new MofangCourseForm();
                    String courseUrl = userInfoDto.getCourseUrl();
                    Matcher matcher = compile.matcher(courseUrl);
                    boolean b = matcher.find();
                    String group = matcher.group();

                    //课程id
                    int courseId = Integer.parseInt(group);
                    mofangCourseForm.setCourseId(courseId);
                    //用户id
                    mofangCourseForm.setUserId(mofangLogin.getId());
                    //表单id 29
                    mofangCourseForm.setFormId(29);
                    mofangCourseForm.setCreateTime(LocalDateTime.now());
                    mofangCourseForm.setLastUpdateTime(LocalDateTime.now());
                    mofangCourseForm.setDeptName(userInfoDto.getDeptName());
                    mofangCourseForm.setCourseName(userInfoDto.getCourseName());


                    MofangCourseForm courseForm = mofangCourseFormService.lambdaQuery().eq(MofangCourseForm::getUserId, mofangLogin.getId()).eq(MofangCourseForm::getCourseId, courseId).eq(MofangCourseForm::getFormId, mofangCourseForm.getFormId()).one();
                    if (courseForm == null) {
                        //保存
                        mofangCourseFormService.save(mofangCourseForm);
                    }


                }
            }

        }
    }

    /**
     * 健康打卡
     */
    @Scheduled(cron = "0 0 7 * * ?")
    public void sign() {
        List<MofangLogin> list = mofangLoginService.lambdaQuery().eq(MofangLogin::getStatus, 2).list();
        for (MofangLogin mofangLogin : list) {
            try {
                TypeReference<HashMap<String, String>> valueTypeRef = new TypeReference<HashMap<String, String>>() {
                };
                String temp = "";
                HashMap<String, String> cookie = OBJECT_MAPPER.readValue(mofangLogin.getCookies(), valueTypeRef);
                List<MofangCourseForm> courseList = mofangCourseFormService.lambdaQuery().eq(MofangCourseForm::getUserId, mofangLogin.getId()).list();
                for (MofangCourseForm mofangCourseForm : courseList) {
                    try {
                        Integer courseId = mofangCourseForm.getCourseId();
                        Integer formId = mofangCourseForm.getFormId();
                        List<FormRecordListDto> signRecord = MoFangUtil.getSignRecord(cookie, courseId, formId);
                        if (!signRecord.isEmpty()) {
                            FormRecordListDto formRecordListDto = signRecord.get(0);
                            //获取表单
                            HashMap<String, String> map = MoFangUtil.getFormRecDetail(cookie, courseId, formId, formRecordListDto.getId());
                            //提交表单结果
                            String formResult = MoFangUtil.submitForm(cookie, map, courseId, formId);
                            //如果是空白
                            if (StrUtil.isBlank(formResult)) {
                                //cookies过期
                                MimeMessage message = sender.createMimeMessage();
                                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
                                mimeMessageHelper.setFrom("loveHuaHua5221314@163.com");
                                mimeMessageHelper.setTo(mofangLogin.getEmail());
                                mimeMessageHelper.setSubject("打卡日报");
                                mimeMessageHelper.setText("您的cookies过期了,账号已为你自动删除,如果还需要此服务,请在微信中打开 https://zhihui.jxwazx.cn/ ", true);
                                sender.send(message);
                                //根据用户id 删除课程
                                mofangCourseFormService.lambdaUpdate().eq(MofangCourseForm::getUserId, mofangLogin.getId()).remove();
                                //根据用户id 删除账号
                                mofangLoginService.lambdaUpdate().eq(MofangLogin::getId, mofangLogin.getId()).remove();
                            } else {
                                temp = formResult;
                                MimeMessage message = sender.createMimeMessage();
                                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
                                mimeMessageHelper.setFrom("loveHuaHua5221314@163.com");
                                mimeMessageHelper.setTo(mofangLogin.getEmail());
                                mimeMessageHelper.setSubject("打卡日报");
                                mimeMessageHelper.setText(formResult, true);
                                sender.send(message);
                            }

                        }
                    } catch (Exception e) {
                        MimeMessage message = sender.createMimeMessage();
                        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
                        mimeMessageHelper.setFrom("loveHuaHua5221314@163.com");
                        mimeMessageHelper.setTo("aihuahua522@qq.com");
                        mimeMessageHelper.setSubject("打卡日报");
                        mimeMessageHelper.setText("程序bug 有人打卡失败了", true);
                        log.error("错误 {},temp:{}", mofangLogin.getEmail(), temp);
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
